package com.bbcloud.service.impl;

import com.bbcloud.common.Const;
import com.bbcloud.common.ServerResponse;
import com.bbcloud.common.TokenCache;
import com.bbcloud.common.ValidCodeCache;
import com.bbcloud.dao.DeviceMapper;
import com.bbcloud.dao.UserMapper;
import com.bbcloud.pojo.Device;
import com.bbcloud.pojo.User;
import com.bbcloud.service.IFileService;
import com.bbcloud.service.IUserService;
import com.bbcloud.util.EmailUtil;
import com.bbcloud.util.IDUtil;
import com.bbcloud.util.MD5Util;
import com.bbcloud.util.PropertiesUtil;
import com.bbcloud.vo.UserVo;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by liuzhu on 2018/11/2.
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService{


    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IFileService iFileService;

    @Override
    public ServerResponse<UserVo> login(String account, String password) {
        int resultCount = userMapper.checkAccount(account);
        if (resultCount == 0){
            return ServerResponse.createByErrorMessage("Account does not exist!");
        }
        String md5Password = MD5Util.MD5EncodeUtf8(password);
        User user = userMapper.selectLogin(account,md5Password);
        if (user == null){
            return ServerResponse.createByErrorMessage("password is wrong!");
        }
        user.setPassword(StringUtils.EMPTY);
        String forgetToken = UUID.randomUUID().toString();
        TokenCache.setKey(TokenCache.TOKEN_PREFIX+account,forgetToken);
        List<Device> deviceList = deviceMapper.selectDevicesWithUserId(user.getUserId());
        UserVo userVo = new UserVo();
        userVo.setUser(user);
        userVo.setToken(forgetToken);
        userVo.setDevices(deviceList);
        return ServerResponse.createBySuccess("login success!",userVo);
    }

    public ServerResponse getValidCode(String account){
        int count = (int)((Math.random()*9+1)*100000);
        String validCode = String.valueOf(count);
        ValidCodeCache.setKey(ValidCodeCache.VALID_PREFIX+account,validCode);
        EmailUtil.sample(account,validCode);
        return ServerResponse.createBySuccess();
    }

    public ServerResponse register(String account, String validCode, String password,String invitationCode) {
        int resultCount = userMapper.checkAccount(account);
        if (resultCount>0){
            return ServerResponse.createByErrorMessage("Account has already exist!");
        }
        String valid = ValidCodeCache.getKey(ValidCodeCache.VALID_PREFIX+account);
        if (StringUtils.isBlank(valid)){
            return ServerResponse.createByErrorMessage("valid invalid or expired");
        }
        int invitationRow = userMapper.isHaveInvitationCode(invitationCode);
        if (invitationRow == 0){
            return ServerResponse.createByErrorMessage("invitation code is wrong");
        }
        Device device = deviceMapper.selectByinvitationCode(invitationCode);
        if (StringUtils.equals(validCode,valid)){
            User user = new User();
            user.setUserType(Const.UserType.ROLE_CUSTOMER);
            user.setEmail(account);
            user.setPassword(MD5Util.MD5EncodeUtf8(password));
            user.setUserName(StringUtils.substringBefore(account,"@"));
            user.setServerId("0000000000000000");   //16个0
            String userId = IDUtil.UserId();
            user.setUserId(userId);
            device.setUserId(userId);
            user.setSex(Const.Sex.SEX_UNKNOW);
            int rowCount = userMapper.insert(user);
            if (rowCount == 0){
                return ServerResponse.createByErrorMessage("注册失败");
            }
            deviceMapper.updateByPrimaryKeySelective(device);
            return ServerResponse.createBySuccessMessage("注册成功");
        }else {
            return ServerResponse.createByErrorMessage("valid invalid or expired");
        }
    }

    public ServerResponse<User>getUserInfo(String account,String token){
        int resultCount = userMapper.checkAccount(account);
        if (resultCount == 0){
            return ServerResponse.createByErrorMessage("User does not exist!");
        }
        String tokenValid = TokenCache.getKey(TokenCache.TOKEN_PREFIX+account);
        if (StringUtils.equals(tokenValid,token)){
            User user = userMapper.getUserInfo(account);
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorMessage("Please log in again");
    }

    public ServerResponse<String> forgetResetPassword(String account,String password,String validCode){
        int resultCount = userMapper.checkAccount(account);
        if (resultCount<=0){
            return ServerResponse.createByErrorMessage("User does not exist!");
        }
        String valid = ValidCodeCache.getKey(ValidCodeCache.VALID_PREFIX+account);
        if (StringUtils.isBlank(valid)){
            return ServerResponse.createByErrorMessage("valid invalid or expired");
        }
        if (StringUtils.equals(validCode,valid)){
            String md5Password = MD5Util.MD5EncodeUtf8(password);
            int rowCount = userMapper.updatePasswordByAccount(account,md5Password);
            if (rowCount>0){
                return ServerResponse.createBySuccessMessage("修改密码成功");
            }
        }else {
            return ServerResponse.createByErrorMessage("valid invalid or expired");
        }
        return ServerResponse.createByErrorMessage("修改密码失败");
    }

    public ServerResponse isLogin(String account,String token){
        String tokenValid = TokenCache.getKey(TokenCache.TOKEN_PREFIX+account);
        if (!StringUtils.equals(tokenValid,token)){
            return ServerResponse.createByError();
        }
        return ServerResponse.createBySuccess();
    }

    public ServerResponse uploadHeadImage(MultipartFile file, String path,String userId){
        String targetFileName = iFileService.upload(file,path);
        String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
        Map fileMap = Maps.newHashMap();
        fileMap.put("uri",targetFileName);
        fileMap.put("url",url);
        User user = new User();
        user.setUserId(userId);
        user.setHeadImage(url);
        userMapper.updateByPrimaryKeySelective(user);
        user = userMapper.selectUser(userId);
        return ServerResponse.createBySuccess();
    }
}
